"""
RedFire框架异常类
=================

定义框架级别的异常类，提供统一的错误处理机制。
"""

from typing import Any, Dict, Optional


class RedFireException(Exception):
    """
    RedFire框架基础异常类
    
    所有框架异常的基类，提供统一的异常处理接口。
    """
    
    def __init__(
        self,
        message: str,
        error_code: Optional[str] = None,
        details: Optional[Dict[str, Any]] = None
    ):
        """
        初始化异常
        
        Args:
            message: 错误消息
            error_code: 错误代码
            details: 错误详情
        """
        super().__init__(message)
        self.message = message
        self.error_code = error_code or "REDFIRE_ERROR"
        self.details = details or {}
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "error_code": self.error_code,
            "message": self.message,
            "details": self.details
        }


class ConfigurationError(RedFireException):
    """配置错误"""
    
    def __init__(self, message: str, config_key: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="CONFIG_ERROR",
            details={"config_key": config_key} if config_key else {}
        )


class ServiceError(RedFireException):
    """服务错误"""
    
    def __init__(self, message: str, service_name: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="SERVICE_ERROR",
            details={"service_name": service_name} if service_name else {}
        )


class DatabaseError(RedFireException):
    """数据库错误"""
    
    def __init__(self, message: str, operation: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="DATABASE_ERROR",
            details={"operation": operation} if operation else {}
        )


class DatabaseTransactionError(DatabaseError):
    """数据库事务错误"""
    
    def __init__(self, message: str, transaction_id: Optional[str] = None):
        super().__init__(
            message=message,
            operation="transaction"
        )
        self.details["transaction_id"] = transaction_id


class AuthenticationError(RedFireException):
    """认证错误"""
    
    def __init__(self, message: str = "Authentication failed"):
        super().__init__(
            message=message,
            error_code="AUTH_ERROR"
        )


class AuthorizationError(RedFireException):
    """授权错误"""
    
    def __init__(self, message: str = "Authorization failed"):
        super().__init__(
            message=message,
            error_code="AUTHZ_ERROR"
        )


class ValidationError(RedFireException):
    """验证错误"""
    
    def __init__(self, message: str, field: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="VALIDATION_ERROR",
            details={"field": field} if field else {}
        )


class CacheError(RedFireException):
    """缓存错误"""
    
    def __init__(self, message: str, cache_key: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="CACHE_ERROR",
            details={"cache_key": cache_key} if cache_key else {}
        )


class EventError(RedFireException):
    """事件处理错误"""
    
    def __init__(self, message: str, event_type: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="EVENT_ERROR",
            details={"event_type": event_type} if event_type else {}
        )


# 用户服务相关异常
class UserNotFoundException(RedFireException):
    """用户未找到异常"""
    
    def __init__(self, message: str = "User not found", user_id: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="USER_NOT_FOUND",
            details={"user_id": user_id} if user_id else {}
        )


class InvalidCredentialsError(AuthenticationError):
    """无效凭证错误"""
    
    def __init__(self, message: str = "Invalid credentials"):
        super().__init__(message=message)


class UserAlreadyExistsException(RedFireException):
    """用户已存在异常"""
    
    def __init__(self, message: str = "User already exists", identifier: Optional[str] = None):
        super().__init__(
            message=message,
            error_code="USER_ALREADY_EXISTS",
            details={"identifier": identifier} if identifier else {}
        )


class ValidationException(ValidationError):
    """验证异常（别名，保持兼容性）"""
    pass
